package com.atguigu.gulimall.juc.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ReenterLockDemoPerson implements Runnable{
    public synchronized void sendSms(){
        System.out.println(Thread.currentThread().getName()+" \t sendSms");
        sendEmail();
    }
    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getName()+" \t sendEmail");
    }

    @Override
    public void run() {
        get();
    }

    Lock lock = new ReentrantLock();
    public void get(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t get");
            set();
        }finally {
            lock.unlock();
        }
    }

    public void set(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t set");
        }finally {
            lock.unlock();
        }
    }
}

/**
 * 可重入锁(也叫做递归锁)
 * 指的是同一线程外层函数获得锁后,内层敌对函数任然能获取该锁的代码
 * 在同一线程外外层方法获取锁的时候,在进入内层方法会自动获取锁
 *
 *  也就是说,线程可以进入任何一个它已经标记的锁所同步的代码块
 */
public class ReenterLockDemo {
    public static void main(String[] args) {
        ReenterLockDemoPerson person = new ReenterLockDemoPerson();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                person.sendSms();
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(person,String.format("i%s",i)).start();
        }
    }
}
